package com.zjs.express.utils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 数据库工具类
 */
public class DBUtils extends DruidUtil {

    //1.定义变量
    private Connection connection;
    private PreparedStatement pps;
    private ResultSet resultSet;
    private int count;//存储收影响的行数

    /**
     * 查询方法
     *
     * @param sql
     * @param params
     * @return
     */
    public ResultSet query(String sql, Object[] params) {
        getPps(sql);
        param(params);
        try {
            resultSet = pps.executeQuery();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return resultSet;
    }

    /**
     * 插入数据方法
     *
     * @param sql
     * @param params
     * @return
     */
    public boolean insert(String sql, Object[] params) {
        int count = base(sql, params);
        if (count > 0) {
            return true;
        }
        return false;
    }

    /**
     * 删除数据方法
     *
     * @param sql
     * @param params
     * @return
     */
    public boolean delete(String sql, Object[] params) {
        int count = base(sql, params);
        if (count > 0) {
            return true;
        }
        return false;
    }

    /**
     * 更新数据方法
     *
     * @param sql
     * @param params
     * @return
     */
    public boolean update(String sql, Object[] params) {
        int count = base(sql, params);
        if (count > 0) {
            return true;
        }
        return false;
    }

    //4.获取连接和得到预状态通道
    protected PreparedStatement getPps(String sql) {
        try {
            connection = getConnection();
            pps = getConnection().prepareStatement(sql);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return pps;
    }

    //5.绑定参数  List保存的是给占位符所赋的值
    protected void param(Object[] params) {
        if (params != null && params.length > 0) {
            for (int i = 0; i < params.length; i++) {
                try {
                    pps.setObject(i + 1, params[i]);
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }

    //6.执行操作(增删改+查询)
    protected int base(String sql, Object[] params) {
        getPps(sql);
        param(params);
        try {
            count = pps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return count;
    }


    //8.关闭资源
    protected void closeAll() {
        try {
            if (connection != null) {
                connection.close();
            }
            if (pps != null) {
                pps.close();
            }

            if (resultSet != null) {
                resultSet.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
